package com.linkage.jz.bankruptcy.activity.Main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.kelin.scrollablepanel.library.ScrollablePanel;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Msg.MsgDetailActivity;
import com.linkage.jz.bankruptcy.adapter.ScrollablePanelAdapter;
import com.linkage.jz.bankruptcy.bean.DateInfo;
import com.linkage.jz.bankruptcy.bean.OrderInfo;
import com.linkage.jz.bankruptcy.bean.RoomInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.linkage.jz.bankruptcy.utils.Utils.StringToLeng;

public class ShowRateListActivity extends Activity {
    public static final SimpleDateFormat DAY_UI_MONTH_DAY_FORMAT = new SimpleDateFormat("MM-dd");
    public static final SimpleDateFormat WEEK_FORMAT = new SimpleDateFormat("EEE", Locale.US);
    public  ScrollablePanelAdapter scrollablePanelAdapter;
    private ShapeLoadingDialog shapeLoadingDialog ;
    private  ScrollablePanel scrollablePanel;
    Button top_back,top_mune;
    TextView top_title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_showratelist);

        top_title = findViewById(R.id.top_title);
        top_mune = findViewById(R.id.top_mune);
        top_back = findViewById(R.id.top_back);

        top_mune.setVisibility(View.INVISIBLE);
        top_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
               finish();
            }
        });
        top_title.setText("人民银行贷款基准利率");

         scrollablePanel = (ScrollablePanel) findViewById(R.id.scrollable_panel);
         scrollablePanelAdapter = new ScrollablePanelAdapter();

//        generateTestData(scrollablePanelAdapter);
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        scrollablePanel.setPanelAdapter(scrollablePanelAdapter);
        scrollablePanel.setHorizontalScrollBarEnabled(true);
        scrollablePanel.setHorizontalFadingEdgeEnabled(true);
        getData();
        super.onCreate(savedInstanceState);
    }

    private void generateTestData(String str) {

        try {
//            String str = "{\"code\":0,\"msg\":\"查询成功\",\"data\":[{\"id\":\"1\",\"lessHalfYearRate\":4.35,\"halfYear2Year\":4.35,\"year2ThreeYear\":4.75,\"threeYear2FiveYear\":4.75,\"fiveYearMore\":4.9,\"time\":1445616000,\"opBy\":\"\",\"opAt\":1445616000,\"delFlag\":false}, {\"id\":\"2\",\"lessHalfYearRate\":4.6,\"halfYear2Year\":4.6,\"year2ThreeYear\":5.0,\"threeYear2FiveYear\":5.0,\"fiveYearMore\":5.15,\"time\":1440518400,\"opBy\":\"\",\"opAt\":1440518400,\"delFlag\":false}, {\"id\":\"3\",\"lessHalfYearRate\":4.85,\"halfYear2Year\":4.85,\"year2ThreeYear\":5.25,\"threeYear2FiveYear\":5.25,\"fiveYearMore\":5.4,\"time\":1435420800,\"opBy\":\"\",\"opAt\":1435420800,\"delFlag\":false}, {\"id\":\"4\",\"lessHalfYearRate\":5.1,\"halfYear2Year\":5.1,\"year2ThreeYear\":5.5,\"threeYear2FiveYear\":5.5,\"fiveYearMore\":5.65,\"time\":1431273600,\"opBy\":\"\",\"opAt\":1431273600,\"delFlag\":false}, {\"id\":\"5\",\"lessHalfYearRate\":5.35,\"halfYear2Year\":5.35,\"year2ThreeYear\":5.75,\"threeYear2FiveYear\":5.75,\"fiveYearMore\":5.9,\"time\":1425139200,\"opBy\":\"\",\"opAt\":1425139200,\"delFlag\":false}, {\"id\":\"6\",\"lessHalfYearRate\":5.6,\"halfYear2Year\":5.6,\"year2ThreeYear\":6.0,\"threeYear2FiveYear\":6.0,\"fiveYearMore\":6.15,\"time\":1416585600,\"opBy\":\"\",\"opAt\":1416585600,\"delFlag\":false}, {\"id\":\"7\",\"lessHalfYearRate\":5.6,\"halfYear2Year\":6.0,\"year2ThreeYear\":6.15,\"threeYear2FiveYear\":6.4,\"fiveYearMore\":6.55,\"time\":1341504000,\"opBy\":\"\",\"opAt\":1341504000,\"delFlag\":false}]}";
            JSONObject ob = new JSONObject(str);
            JSONArray ary = ob.optJSONArray("data");

            List<RoomInfo> roomInfoList = new ArrayList<>();
            List<OrderInfo> orderInfoList = new ArrayList<>();
            List<List<OrderInfo>> ordersList = new ArrayList<>();
            scrollablePanelAdapter.setRoomInfoList(roomInfoList);

            List<DateInfo> dateInfoList = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();



            DateInfo dateInfo1 = new DateInfo();

            dateInfo1.setDate("六个月以内");
            dateInfo1.setWeek("（含六个月）");
            dateInfoList.add(dateInfo1);

            DateInfo dateInfo2 = new DateInfo();

            dateInfo2.setDate("六个月至一年");
            dateInfo2.setWeek("（含一年）");
            dateInfoList.add(dateInfo2);

            DateInfo dateInfo3 = new DateInfo();

            dateInfo3.setDate("一年至三年");
            dateInfo3.setWeek("（含三年）");
            dateInfoList.add(dateInfo3);

            DateInfo dateInfo4 = new DateInfo();

            dateInfo4.setDate("三年至五年");
            dateInfo4.setWeek("（含五年）");
            dateInfoList.add(dateInfo4);



            DateInfo dateInfo5 = new DateInfo();
            dateInfo5.setDate("五年以上");
            dateInfo5.setWeek("");
            dateInfoList.add(dateInfo5);

            DateInfo dateInfo6 = new DateInfo();
            dateInfo6.setDate("六年以上");
            dateInfo6.setWeek("");
            dateInfoList.add(dateInfo6);


            scrollablePanelAdapter.setDateInfoList(dateInfoList);
            for (int i = ary.length()-1; i >-1; i--) {
                JSONObject json = (JSONObject) ary.get(i);
                String time = json.optString("opAt");
                long l_time = StringToLeng(time)*1000;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Date dateOld = new Date(l_time); // 根据long类型的毫秒数生命一个date类型的时间
                String strTime = sdf.format(dateOld);


                RoomInfo roomInfo = new RoomInfo();
                roomInfo.setRoomType(strTime);
                roomInfo.setRoomId(i);
                roomInfo.setRoomName("");
                roomInfoList.add(roomInfo);


                String lessHalfYearRate = json.optString("lessHalfYearRate");
                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setGuestName(lessHalfYearRate);
                orderInfo.setBegin(true);
                orderInfo.setStatus(OrderInfo.Status.CHECK_IN);
                orderInfoList.add(orderInfo);

                String halfYear2Year = json.optString("halfYear2Year");
                OrderInfo orderInfo1 = new OrderInfo();
                orderInfo1.setGuestName(halfYear2Year);
                orderInfo1.setBegin(true);
                orderInfo1.setStatus(OrderInfo.Status.CHECK_IN);
                orderInfoList.add(orderInfo1);

                String year2ThreeYear = json.optString("year2ThreeYear");
                OrderInfo orderInfo2 = new OrderInfo();
                orderInfo2.setGuestName(year2ThreeYear);
                orderInfo2.setBegin(true);
                orderInfo2.setStatus(OrderInfo.Status.CHECK_IN);
                orderInfoList.add(orderInfo2);

                String threeYear2FiveYear = json.optString("threeYear2FiveYear");
                OrderInfo orderInfo3 = new OrderInfo();
                orderInfo3.setGuestName(threeYear2FiveYear);
                orderInfo3.setBegin(true);
                orderInfo3.setStatus(OrderInfo.Status.CHECK_IN);
                orderInfoList.add(orderInfo3);

                String fiveYearMore = json.optString("fiveYearMore");
                OrderInfo orderInfo4 = new OrderInfo();
                orderInfo4.setGuestName(fiveYearMore);
                orderInfo4.setBegin(true);
                orderInfo4.setStatus(OrderInfo.Status.CHECK_IN);
                orderInfoList.add(orderInfo4);

               ordersList.add(orderInfoList);


            }


//
//            List<List<OrderInfo>> ordersList = new ArrayList<>();
//            for (int i = 0; i < 30; i++) {
//                List<OrderInfo> orderInfoList = new ArrayList<>();
//                for (int j = 0; j < 14; j++) {
//                    OrderInfo orderInfo = new OrderInfo();
//                    orderInfo.setGuestName("11");
//                    orderInfo.setBegin(true);
//                    orderInfo.setId(j);
//                    orderInfo.setStatus(OrderInfo.Status.CHECK_IN);
////                orderInfo.setStatus(OrderInfo.Status.randomStatus());
////                if (orderInfoList.size() > 0) {
////                    OrderInfo lastOrderInfo = orderInfoList.get(orderInfoList.size() - 1);
////                    if (orderInfo.getStatus().ordinal() == lastOrderInfo.getStatus().ordinal()) {
////                        orderInfo.setId(lastOrderInfo.getId());
////                        orderInfo.setBegin(false);
////                        orderInfo.setGuestName("");
////                    } else {
////                        if (new Random().nextBoolean()) {
////                            orderInfo.setStatus(OrderInfo.Status.BLANK);
////                        }
////                    }
////                }
//                    orderInfoList.add(orderInfo);
//                }
//                ordersList.add(orderInfoList);
//            }
            scrollablePanelAdapter.setOrdersList(ordersList);
            scrollablePanel.setPanelAdapter(scrollablePanelAdapter);
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
        }


    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
//            getToken();
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")

                .build();

        String url = Consts.WEBURL_RATELIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ShowRateListActivity.this,"获取失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();


                final String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                generateTestData(str);
//                                Toast.makeText(RateCalcActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
//                                BankruptcyApp.loginInfo.setEmail(email);
                            }

                        });
//                        finish();

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ShowRateListActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }

                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ShowRateListActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
